//
//  LGMedicineBallPlanController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/29.
//  更新入院进展

#import "LGMedicineBallPlanController.h"
#import "LGMedicineBallSectionView.h"
#import "DatePickerView.h"
#define placeHolder  @"请输入"

@interface LGMedicineBallPlanController ()<UITextViewDelegate>
/**   */
@property (nonatomic , strong)UIScrollView *scrollView;
/**   */
@property (nonatomic , strong)LGMedicineBallSectionView *statusView;
/**   */
@property (nonatomic , strong)LGMedicineBallSectionView *dateView;
/**   */
@property (nonatomic , strong)LGMedicineBallSectionView *remarkView;
/**   */
@property (nonatomic , strong)UITextField *dateTF;
/**   */
@property (nonatomic , strong)UIImageView *dateTip;
/**   */
@property (nonatomic , strong)UITextView *remarkTF;
/**   */
@property (nonatomic , strong)UIButton *saveButton;
/**   */
@property (nonatomic , strong)NSArray *statusArray;
/**   */
@property (nonatomic , strong)NSMutableArray *itemArray;
/**   */
@property (nonatomic , copy)NSString *status;

@end

@implementation LGMedicineBallPlanController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createSubView];
    [self requestData];
    self.remarkView.hidden = self.hiddenRemark;
}
-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.dcb.patient/detail" parameters:@{@"plan_id":self.planids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.status = LGNSString(returnData[@"status"]);
            self.statusArray = returnData[@"status_options"];
            self.dateTF.text = LGNSString(returnData[@"appointment_date"]);
            self.remarkTF.text = LGNSString(returnData[@"remarks"]);
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setStatus:(NSString *)status{
    _status = status;
    if([status isEqualToString:@"4"]){
        //已完成--显示时间
        self.dateView.hidden = NO;
        [self.remarkView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.statusView.mas_bottom).offset(viewPix(88));
        }];

    }else{
        //不显示
        self.dateView.hidden = YES;
        [self.remarkView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.statusView.mas_bottom).offset(viewPix(16));
        }];
    }
}

-(void)setStatusArray:(NSArray *)statusArray{
    _statusArray = statusArray;
    CGFloat topMargin = viewPix(60);
    CGFloat leftMargin = viewPix(12);
    CGFloat itemWidth = (Screen_W-viewPix(56)-viewPix(16))/3.0;
    CGFloat itemHeight = viewPix(32);
    CGFloat bottom = viewPix(72);
    for (NSInteger i=0; i<statusArray.count; i++) {
        NSDictionary *tempDic = statusArray[i];
        UIButton *itemBtn = [UIButton buttonWithTitle:LGNSString(tempDic[@"title"]) titleFont:LGFontWeight(15, UIFontWeightMedium) normalColor:@"#666666" selectColor:@"#FFFFFF"];
        itemBtn.frame = CGRectMake(leftMargin+(itemWidth+viewPix(8))*(i%3), topMargin+(itemHeight+viewPix(8))*(i/3), itemWidth, itemHeight);
        [itemBtn setBackgroundColor:[UIColor colorWithString:@"#F6F6F6"] forState:UIControlStateNormal];
        [itemBtn setBackgroundColor:[UIColor colorWithString:@"#3291FF"] forState:UIControlStateSelected];
        itemBtn.cornerRidus = viewPix(16);
        itemBtn.tag = [tempDic[@"value"] integerValue]+1000;
        itemBtn.selected = [LGNSString(tempDic[@"value"]) isEqualToString:self.status]?YES:NO;
        [itemBtn addTarget:self action:@selector(itemButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self.statusView addSubview:itemBtn];
        [self.itemArray addObject:itemBtn];
        bottom = kMaxY(itemBtn.frame)+viewPix(12);
    }
    [self.statusView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(bottom));
    }];
}

-(void)itemButtonTouched:(UIButton *)sender{
    for (UIButton *button in self.itemArray) {
        button.selected = NO;
    }
    sender.selected = YES;
    NSInteger value = sender.tag - 1000;
    self.status = [NSString stringWithFormat:@"%ld",value];
}

//选择时间
-(void)selectDateAction{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd";
    DatePickerView *pickerView = [[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.beginDate = [formatter stringFromDate:[NSDate date]];
    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectDate = ^(NSString *date) {
        weakSelf.dateTF.text = date;
    };
}


- (void)textViewDidBeginEditing:(UITextView *)textView{
    self.remarkTF.textColor = [UIColor colorWithString:@"#333333"];
    if([textView.text isEqualToString:placeHolder]){
        self.remarkTF.text = @"";
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView{
//    self.content = textView.text;
}

- (void)textViewDidChange:(UITextView *)textView{
    NSString *lang = textView.textInputMode.primaryLanguage; // 键盘输入模式
    NSString *content = textView.text;
    if ([lang isEqualToString:@"zh-Hans"]){
        UITextRange *selectedRange = [textView markedTextRange];
        if (!selectedRange) { // 没有高亮
            if (textView.text.length>500) { // 输入的文字大于设定的长度  这里设置的是200个字符
                textView.text = [textView.text substringToIndex:500];
            }else{
                textView.text = textView.text;
            }
           
            if(textView.text.length>0){
                textView.attributedText = [textView.text attributeString:@{NSFontAttributeName:LGFont(14),NSForegroundColorAttributeName:[UIColor colorWithString:@"#333333"]} lineSpacing:5];
            }
            CGSize maxSize = CGSizeMake(self.remarkTF.size.width, MAXFLOAT);
            CGSize fitSize = [textView sizeThatFits:maxSize];
            CGFloat viewHeight = self.remarkTF.bounds.size.height;
            CGFloat newHeight = fitSize.height;
            NSLog(@">>>???>>>%.2f--%.2f",newHeight,viewHeight);
            if(newHeight > viewPix(79) && newHeight != viewHeight){
        //        NSLog(@">>>???>>>%.2f--%.2f",newHeight,viewHeight);
                [self.remarkView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.equalTo(@(newHeight+viewPix(72)));
                }];
                CGFloat bottom = kMinY(self.remarkView.frame)+newHeight+viewPix(72);
                self.scrollView.contentSize = CGSizeMake(Screen_W, bottom+viewPix(50));
            }
        }
    }else{
        if (textView.text.length>500) {
            textView.text = [textView.text substringToIndex:500];
        }else{
            textView.text = textView.text;
        }
        if(textView.text.length>0){
            textView.attributedText = [textView.text attributeString:@{NSFontAttributeName:LGFont(14),NSForegroundColorAttributeName:[UIColor colorWithString:@"#333333"]} lineSpacing:5];
        }
        CGSize maxSize = CGSizeMake(Screen_W-viewPix(56), MAXFLOAT);
        CGSize fitSize = [textView sizeThatFits:maxSize];
        CGFloat viewHeight = self.remarkTF.bounds.size.height;
        CGFloat newHeight = fitSize.height;
        NSLog(@">>>???>>>%.2f--%.2f",newHeight,viewHeight);
        if(newHeight > viewPix(79) && newHeight != viewHeight){
    //        NSLog(@">>>???>>>%.2f--%.2f",newHeight,viewHeight);
            [self.remarkView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(@(newHeight+viewPix(72)));
            }];
            CGFloat bottom = kMinY(self.remarkView.frame)+newHeight+viewPix(72);
            self.scrollView.contentSize = CGSizeMake(Screen_W, bottom+viewPix(50));

        }
    }
}

//保存
-(void)saveButtonAction{
    if(!_status || _status.length == 0){
        [TooltipView showMessage:@"请选择入园状态" offset:0];
    }else{
        [RequestUtil withPOST:@"/doctor/patient.dcb.patient/updateStatus" parameters:@{@"plan_ids":self.planids,@"status":self.status,@"appointment_date":self.dateTF.text,@"remarks":self.remarkTF.text} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMedicinBallData" object:nil];
                [TooltipView showMessage:@"保存成功" offset:0];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"保存失败，请重试" offset:0];
        }];
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.navigationView.title = @"更新入院进展";
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
    self.navigationView.backgroundColor = [UIColor colorWithString:@"#E5F3FF"];
    [self.view addSubview:self.navigationView];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.statusView];
    [self.scrollView addSubview:self.dateView];
    [self.scrollView addSubview:self.remarkView];
    [self.view addSubview:self.saveButton];
    [self.dateView addSubview:self.dateTF];
    [self.dateView addSubview:self.dateTip];
    [self.remarkView addSubview:self.remarkTF];
    
    [self.statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(viewPix(16));
        make.left.equalTo(self.view).offset(viewPix(16));
        make.right.equalTo(self.view).offset(-viewPix(16));
        make.height.equalTo(@(viewPix(104)));
    }];
    [self.dateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.statusView.mas_bottom).offset(viewPix(16));
        make.left.right.equalTo(self.statusView);
        make.height.equalTo(@(viewPix(56)));
    }];
    [self.remarkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.statusView.mas_bottom).offset(viewPix(16));
        make.left.right.equalTo(self.statusView);
        make.height.equalTo(@(viewPix(156)));
    }];
    [self.dateTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dateTF.mas_right);
        make.centerY.equalTo(self.dateTF);
        make.width.height.equalTo(@(viewPix(12)));
    }];
    [self.remarkTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.remarkView).offset(viewPix(60));
        make.left.equalTo(self.remarkView).offset(viewPix(12));
        make.right.equalTo(self.remarkView).offset(-viewPix(12));
        make.bottom.equalTo(self.remarkView).offset(-viewPix(12));
    }];
}
-(UIScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(65)-bottomSafeBarHeight/4.0)];
        _scrollView.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
        _scrollView.contentSize = CGSizeMake(Screen_W, Screen_H-topBarHeight-viewPix(72));
    }
    return _scrollView;
}
-(LGMedicineBallSectionView *)statusView{
    if(!_statusView){
        _statusView = [[LGMedicineBallSectionView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(16)+topBarHeight, Screen_W-viewPix(32), viewPix(144))];
        _statusView.iconView.image = [UIImage imageNamed:@"药球管理-状态"];
        _statusView.titleLabel.text = @"入院状态";
        _statusView.lineView.hidden = NO;
    }
    return _statusView;
}

-(LGMedicineBallSectionView *)dateView{
    if(!_dateView){
        _dateView = [[LGMedicineBallSectionView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(16)+kMaxY(self.statusView.frame), Screen_W-viewPix(32), viewPix(56))];
        _dateView.iconView.image = [UIImage imageNamed:@"药球管理-时间"];
        _dateView.titleLabel.text = @"安排入院时间(选填)";
        _dateView.lineView.hidden = YES;
        _dateView.hidden = YES;
        [_dateView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDateAction)]];
    }
    return _dateView;
}

-(LGMedicineBallSectionView *)remarkView{
    if(!_remarkView){
        _remarkView = [[LGMedicineBallSectionView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(16)+kMaxY(self.dateView.frame), Screen_W-viewPix(32), viewPix(151))];
        _remarkView.iconView.image = [UIImage imageNamed:@"药球管理-备注"];
        _remarkView.titleLabel.text = @"备注(选填)";
        _remarkView.lineView.hidden = NO;
    }
    return _remarkView;
}

-(UITextField *)dateTF{
    if(!_dateTF){
        _dateTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(150), 0, Screen_W-viewPix(202), viewPix(56))];
        _dateTF.textColor = [UIColor colorWithString:@"#333333"];
        _dateTF.textAlignment = NSTextAlignmentRight;
        _dateTF.userInteractionEnabled = NO;
        _dateTF.placeholder = @"请选择";
        _dateTF.font = LGFont(16);
    }
    return _dateTF;
}

-(UIImageView *)dateTip{
    if(!_dateTip){
        _dateTip = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTip12"]];
    }
    return _dateTip;
}

-(UITextView *)remarkTF{
    if(!_remarkTF){
        _remarkTF = [[UITextView alloc]init];
        _remarkTF.backgroundColor = [UIColor colorWithString:@"#F0F7FF"];
        _remarkTF.tintColor = [UIColor colorWithString:@"#333333"];
        _remarkTF.textColor = [UIColor colorWithString:@"#333333"];
        _remarkTF.textAlignment = NSTextAlignmentLeft;
        _remarkTF.font = LGFont(14);
        _remarkTF.delegate = self;
        _remarkTF.cornerRidus = 5;
    }
    return _remarkTF;
}

-(UIButton *)saveButton{
    if(!_saveButton){
        _saveButton = [UIButton buttonWithTitle:@"保存" topMargin:Screen_H-viewPix(60)-bottomSafeBarHeight/4.0];
        [_saveButton addTarget:self action:@selector(saveButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}
-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}
@end
